<template>
  <div class="bar-chart-container">
    <!-- ECharts 容器 -->
    <div :id="chartId" class="chart-content"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "BarChart",
  props: {
    // 图表数据：对象数组，格式 [{xAxis: '横轴值', seriesData: 数值}, ...]
    chartData: {
      type: Array,
      required: true,
      default: () => [],
      // 验证每个对象必须包含xAxis和seriesData
      validator: (value) => {
        return (
          Array.isArray(value) &&
          value.every((item) => {
            return (
              item &&
              typeof item === "object"
               &&
              "date" in item &&
              "completed_qty" in item
            );
          })
        );
      },
    },
    // 图表标题
    title: {
      type: String,
      default: "",
    },
    // y 轴名称
    yAxisName: {
      type: String,
      default: "",
    },
    chartId: { type: String, default: "Bar-chart" },
  },
  data() {
    return {
      myChart: null,
      backgroundData: [], // 背景柱数据
      maxValue: 0, // 数据最大值（用于背景柱高度）
    };
  },
  mounted() {
    this.initChart();
  },
  watch: {
    // 监听chartData变化，更新图表
    chartData: {
      deep: true, // 深度监听对象数组变化
      handler(newVal) {
        this.updateChart(newVal);
      },
    },
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.myChart) {
      this.myChart.dispose();
      this.myChart = null;
    }
  },
  methods: {
    initChart() {
      const chartDom = document.getElementById(this.chartId);
      if (chartDom) {
        this.myChart = echarts.init(chartDom);
        this.updateChart(this.chartData);
      }
    },
    // 格式化seriesData为数字（处理非数字情况）
    formatSeriesData(val) {
      const num = Number(val);
      return isNaN(num) ? 0 : num;
    },
    updateChart(data) {
      if (!this.myChart || !Array.isArray(data) || data.length === 0) return;

      // 从对象数组中提取x轴数据（xAxis）和系列数据（seriesData）
      const xAxisData = data.map((item) => item.date || ""); // 处理xAxis为空的情况
      const seriesData = data.map((item) =>
        this.formatSeriesData(item.completed_qty)
      ); // 确保为数字

      // 计算最大值（用于背景柱高度）
      this.maxValue = seriesData.length > 0 ? Math.max(...seriesData) : 0;
      // 背景数据长度与系列数据一致，值为最大值
      this.backgroundData = new Array(seriesData.length).fill(this.maxValue);

      const option = {
        title: {
          text: this.title,
          left: "left",
          textStyle: {
            color: "#fff",
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "none",
          },
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: "#ccc",
            },
          },
          axisLabel: {
            color: "#fff",
            fontSize:7,
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          nameGap: 25, // 名称与轴线的距离
          name: this.yAxisName,
          nameTextStyle: {
            color: "#fff", // 坐标轴名称的颜色
            fontSize: "20", // 文字字体大小
            align: "right", // 文字水平对齐方式，默认自动（'left'，'center'，'right'）
            verticalAlign: "bottom", // 文字垂直对齐方式，默认自动（'top'，'middle'，'bottom'
          },
          axisLine: {
            lineStyle: {
              color: "#ccc",
            },
          },
          nameGap: 20,
          axisLabel: {
            color: "#fff",
            fontSize: 16,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        series: [
          {
            type: "pictorialBar",
            symbolRepeat: "fixed",
            symbolMargin: 2,
            symbolSize: [10, 10],
            symbol: "rect",
            barWidth: "10%",
            itemStyle: {
              color: "rgba(255, 255, 255, 0.15)",
              borderRadius: 6,
            },
            tooltip: {
              trigger: "axis",
              show: false,
            },
            z: 0,
            data: this.backgroundData,
          },
          {
            type: "pictorialBar",
            symbolRepeat: "fixed",
            symbolMargin: 2,
            symbol: "rect",
            symbolClip: true,
            symbolSize: [10, 10],
            name: this.title,
            data: seriesData,
            barWidth: "10%",
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#6495ED" },
                { offset: 1, color: "#6495EB" },
              ]),
              borderRadius: [6, 6, 0, 0],
            },
            label: {
              show: false,
              position: "top",
              color: "#fff",
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#6495Ee" },
                  { offset: 1, color: "#6495EC" },
                ]),
              },
            },
          },
        ],
        grid: {
          left: "2%",
          top: "11%",
          right: "0",
          bottom: "1%",
          containLabel: true,
        },
      };
      this.myChart.setOption(option);
    },
  },
};
</script>

<style scoped>
.bar-chart-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
}
.chart-content {
  width: 100%;
  height: 100%;
}
</style>